import axios from 'axios';
// import Qs from 'qs'
import router from '@/router/index';
import store from '@/store/index';
import { Message } from 'element-ui';

const toLogin = () => {
    router.push({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    });

};

const service = axios.create({
    baseURL: GlobalConfig.apiBaseurl + 'OverrunService.svc/',
    timeout: 30000,
    responseType: 'json'
    // withCredentials: true
});

service.interceptors.request.use(
    request => {
        request.headers['Content-Type'] = 'text/plain';
        if (request.method == 'post') {
            if (request.data instanceof FormData) {
                if (store.getters['user/isLogin']) {
                }
            } else {
                // 带上 token
                if (request.data == undefined) {
                    request.data = {};
                }
                if (store.getters['user/isLogin']) {
                    request.data.AutoLogin = store.state.user.token;
                    request.data.LoginName = store.state.user.account;
                }
                // request.data = Qs.stringify(request.data)
            }
        } else {
            // 带上 token
            if (request.params == undefined) {
                request.params = {};
            }
            if (store.getters['user/isLogin']) {
                request.params.AutoLogin = store.state.user.token;
                request.params.LoginName = store.state.user.account;
            }
        }
        return request;
    }
);

service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.status !== '0') {
            return Promise.reject(response.data);
        } else {
            return response.data;
        }
    },
    error => {
        return Promise.reject(error);
    }
);

export default service;
